#!/usr/bin/python
#example code, lecture 5

#a=2**1000
#print a
#b=2**999
#print b
#print a/b
#
#x=0.1
#print x
#s=0.0
#print s
#
#for i in range( 10 ):
#    s+=0.1
#
#print s

#import math
#a = math.sqrt( 2 )
#print a
#print a*a==2

#compute square root of x using bi-section method
#there is a bug in this function, Prof. John Guttag
def squareRootBi( x,epsilon ):
    """Assuse x >= 0 and epsilon > 0
        Return y, y*y is within epsilon of x"""
    assert x >= 0, 'x must be non-negative, not' + str( x )
    assert epsilon > 0, 'epsilon must be postive, no ' + str( epsilon )
    low = 0
    high = x
    guess = ( low+high )/2.0
    ctr = 1
    trytime = 100

    while abs( guess**2 - x )>epsilon and ctr <= trytime:
        print 'low:', low, 'high:', high, 'guess,', guess
        if guess**2 < x:
            low = guess
        else:
            high = guess
        guess = ( low + high )/2.0
        ctr += 1
    assert ctr <= trytime, 'Iteration count exceeded'  
    print 'Bi method. Num, iteration:',ctr,'estimate:',guess
    return guess

squareRootBi(9,0.0001)
#squareRootBi(3,0.0001)
